import os

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.cvm.v20170312 import cvm_client, models


# 导入腾讯对象存储工具
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

region = 'ap-chengdu'
secret_id = os.environ.get("TENCENTCLOUD_SECRET_ID")
secret_key = os.environ.get("TENCENTCLOUD_SECRET_KEY")
cred = credential.Credential(secret_id, secret_key)
endpoint = 'cos.ap-chengdu.myqcloud.com'
bucket = 'os-images-1306286147'
# 实例化要请求产品(以cvm为例)的client对象，clientProfile是可选的。
client = cvm_client.CvmClient(cred, region)

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Endpoint=endpoint)
# 2. 获取对象存储客户端对象
cos_client = CosS3Client(config)

DryRun = False

try:

  # 查看可用镜像列表
  def describeImages(**kwargs):
    req = models.DescribeImagesRequest()
    print(kwargs)
    print(len(kwargs))
    if len(kwargs) > 0:
      req.Filters = []
      for k in kwargs:
        print('k {} w {}'.format(k, kwargs[k]))
        respFilter = models.Filter()  # 创建Filter对象
        respFilter.Name = k
        respFilter.Values = kwargs[k]
        req.Filters.append(respFilter)

    resp = client.DescribeImages(req)
    return resp.to_json_string(indent=2)
  
  # 导入镜像
  def importImage(ImageName, OsType, OsVersion, ImageUrl, ImageDescription='', Architecture='x86_64'):
    req = models.ImportImageRequest()
    req.Architecture = Architecture
    req.ImageName = ImageName
    req.ImageDescription = ImageDescription
    req.OsType = OsType
    req.OsVersion = OsVersion
    req.ImageUrl = ImageUrl
    req.DryRun = DryRun
    resp = client.ImportImage(req)
    return resp.to_json_string(indent=2)
  
  # 上传镜像
  def uploadImage(file):
    # upload 
    with open(file, 'rb') as fp:
      print('fp:{}'.format(fp))
      response = cos_client.put_object(
          Bucket=bucket,
          Body=fp,
          Key=file,
          StorageClass='STANDARD',
          EnableMD5=False
      )
    
    print('response:{}'.format(response))
    print(response)
  
  # 创建实例
  def createIns(ImageId, InstanceType, InstanceName, zone):
    req = models.RunInstancesRequest()
    req.ImageId = ImageId
    req.InstanceChargeType = 'POSTPAID_BY_HOUR'
    req.InstanceType = InstanceType
    req.InstanceName = InstanceName
    placement = models.Placement()
    placement.zone = zone
    req.Placement = placement
    disk = models.DataDisk()
    disk.DiskSize = 100
    disk.DiskType = 'CLOUD_PREMIUM'
    req.DataDisks=[disk]
    systemDisk = models.SystemDisk()
    systemDisk.DiskSize=50
    systemDisk.DiskType='CLOUD_PREMIUM'
    req.SystemDisk = systemDisk
    InternetAccessible = models.InternetAccessible()
    InternetAccessible.InternetChargeType = 'TRAFFIC_POSTPAID_BY_HOUR'
    InternetAccessible.InternetMaxBandwidthOut = 5
    InternetAccessible.PublicIpAssigned = True
    req.InternetAccessible = InternetAccessible
    LoginSetting = models.LoginSettings()
    LoginSetting.Password = 'lAd{ir5@_ldI6dhnr'
    req.LoginSettings = LoginSetting
    resp = client.RunInstances(req)
    print(resp)

  # 关闭实例
  def shutdownIns(instanceIds):
    req = models.StopInstancesRequest()
    req.InstanceIds = instanceIds
    req.ForceStop = True
    req.DryRun = DryRun
    resp = client.StopInstances(req)
    print(resp)

  # 退还实例
  def terminateInstances(InstanceIds):
    req = models.TerminateInstancesRequest()
    req.InstanceIds = InstanceIds
    req.DryRun = DryRun
    resp = client.TerminateInstances(req)
    print(resp)

  # 查看实例列表
  def DescribeInstances():
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    print(resp)

  DryRun = False

  # print(describeImages())
  # print(describeImages(platform = ['Ubuntu']))

  # print(importImage('Ubuntu-20.04-live-server-amb64.iso', 'Ubuntu', '16', 'https://os-images-1258516577.cos.ap-nanjing.myqcloud.com/Users/justshaw/workspace/edu/nengli-master/nengli-server/nengli/ubuntu-20.04-live-server-amd64.iso'))

  # f = "/Users/justshaw/workspace/edu/nengli-master/nengli-server/nengli/BatchImportFiles/83081cff-3d76-406c-a823-1b6608b87061.iso"
  # uploadImage(f)

  createIns('img-pi0ii46r', 'S3.SMALL1', 'image-ubuntu-server-18.04-lts', 'ap-chengdu-1')

  # shutdownIns(['ins-4euhi8p5', 'ins-pcweaiaz'])

  # terminateInstances(['ins-4euhi8p5', 'ins-pcweaiaz'])

  # DescribeInstances()

except TencentCloudSDKException as err:
  print(err)

